import {Component, OnInit} from '@angular/core';
import {PageEntity} from '../../../core/domain/page.entity';
import {RolesService} from './roles.service';
import {Response} from '../../../core/domain/response';
import {Role} from './domain/role';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {CopyUtil} from '../../../utils/copy.util';
import {Auth} from './domain/auth';
import {User} from '../../../login/user.param';
import {StatusEnum} from '../../../core/enum/status.enum';
import {FilterEnum} from '../../../core/enum/filter.enum';
import {PaginationUtils} from '../../../utils/paginationUtils';
import {NzMessageService} from 'ng-zorro-antd';

@Component({
    selector: 'app-roles',
    templateUrl: './roles.component.html',
    styleUrls: ['./roles.component.scss'],
    providers: [RolesService]
})
export class RolesComponent implements OnInit {
    // 角色列表
    list: Role[] = [];
    // 单个角色
    role: Role = new Role();

    // 分页查询条件
    pageInfo: PageEntity = new PageEntity();
    pageInfo01: PageEntity = new PageEntity();
    displayList = [];
    displayList01 = [];
    // 选中id
    mapOfCheckedId: { [key: string]: boolean } = {};
    mapOfCheckedId01: { [key: string]: boolean } = {};
    isIndeterminate = false;
    isIndeterminate01 = false;
    // 全选状态
    isAllCheck = false;
    isAllCheck01 = false;
    // 是否打开新增编辑框
    isAddEdit = false;
    // 是否打开权限分配框
    isAssigAuthority = false;
    // 是否打开用户分配框
    isAssigUser = false;
    // 是否打开用户选择页面
    isSlectUser = false;
    isRemoveSlectUser = false;

    // 声明角色表单对象
    roleForm: FormGroup;
    // 查询条件name
    seachName = null;
    operator = null;
    alertUserName = null;
    alertNumber = null;

    // 权限树
    modelTree: Auth[] = [];
    // 拥有权限Ids
    authArr: string[] = [];

    // 拥有莫类角色的用户
    authUsers: User[] = [];
    //
    userList: User[] = [];

    constructor(private pageService: RolesService,
                private message: NzMessageService,
                private formBuilder: FormBuilder) {
    }

    ngOnInit() {
        // 初始化分页条件
        this.pageInfo.filters = {
            name: {
                value: null
            }
        };
        // 获取角色列表
        this.pageList();
        // 初始化角色表单对象
        this.initRoleForm();
    }

    /**
     * 初始化角色表单对象
     */
    initRoleForm() {
        this.roleForm = this.formBuilder.group({
            name: [null, [Validators.required]],
            remark: [null, []]
        });
    }

    // 数据请求列表
    pageList() {
        if (this.seachName) {
            this.pageInfo.filters['name'.toString()] = PaginationUtils.filters(this.seachName, FilterEnum.CONTAINS);
        } else {
            delete this.pageInfo.filters['name'.toString()];
        }
        if (this.operator) {
          this.pageInfo.filters.operator = PaginationUtils.filters(this.operator, FilterEnum.CONTAINS);
        } else {
          delete this.pageInfo.filters.operator;
        }
        this.pageService.page(this.pageInfo).subscribe((res: Response) => {
            const {datas, status} = res;
            if (status === StatusEnum.SUCCESS) {
                const {data, totalRecords} = datas;
                this.list = data;
                this.pageInfo.totalRecords = totalRecords;
            }
        });
    }

    // 第几页
    searchPageIndex(event) {
        this.pageInfo.first = event;
        this.pageList();
    }

    // 每页几条
    searchPageSize(event) {
        this.pageInfo.rows = event;
        this.pageInfo.first = 1;
        this.pageList();
    }

    // 第几页
    searchPageIndex01(event) {
        this.pageInfo01.first = event;
        this.pageFn(this.pageInfo01, this.role.id);
    }

    // 每页几条
    searchPageSize01(event) {
        this.pageInfo01.rows = event;
        this.pageInfo01.first = 1;
        this.pageFn(this.pageInfo01, this.role.id);
    }

    /**
     * 当前页数据更改
     * @param $event 状态
     * @param num num 表格类型 1：已选用户 2：添加人员
     */
    currentPageDataChange($event, num: number): void {
        if (num === 1) {
            this.displayList = $event;
        } else {
            this.displayList01 = $event;
        }
        this.refreshStatus(num);
    }

    /**
     * 置换状态
     */
    refreshStatus(num: number): void {
        num === 1 ? this.dealBoolLogic(this.isAllCheck, this.displayList, this.mapOfCheckedId, this.isIndeterminate)
            : this.dealBoolLogic(this.isAllCheck01, this.displayList01, this.mapOfCheckedId01, this.isIndeterminate01);
    }

    /**
     * 状态切换时bool值判断逻辑
     * @param allBool:全选判断
     * @param disArr:当前数组判断
     * @param idObj:id对象
     * @param isInBool:全选状态
     */
    dealBoolLogic(allBool: boolean, disArr: Array<any>, idObj: any, isInBool: boolean): void {
        allBool = disArr.every(item => idObj[item.id]);
        isInBool = disArr.some(item => idObj[item.id]) && !allBool;
    }

    resetSearch(): void {
        this.seachName = null;
        this.operator = null;
        this.pageList();
    }

    /**
     * 全选
     * @param value 选中状态
     * @param num 表格类型 1：已选用户 2：添加人员
     */
    checkAll(value: boolean, num: number): void {
        if (num === 1) {
            this.displayList.forEach(item => (this.mapOfCheckedId[item.userId] = value));
        } else {
            this.displayList01.forEach(item => (this.mapOfCheckedId01[item.id] = value));
        }
        this.refreshStatus(num);
    }

    /**
     * 点打开新增编辑框
     */
    addBtn(): void {
        this.role = new Role();
        this.initRoleForm();
        this.isAddEdit = true;
    }

    /**
     * 编辑角色
     * @param role 角色信息
     */
    editRole(role: Role): void {
        this.role = CopyUtil.deepCopy(role, {});
        this.isAddEdit = true;
    }

    /**
     * 输出数据请求
     */
    delete(ids: string): void {
        this.pageService.delete(ids).subscribe((res: Response) => {
            const {status} = res;
            if (status === StatusEnum.SUCCESS) {
                this.isAddEdit = false;
                this.message.success(res.message);
                this.pageList();
            }
        });
    }

    /**
     * 打开权限分配框
     */
    assigAuthority(roleId: string) {
        this.pageService.viewAuth(roleId).subscribe((res: Response) => {
            const {datas, status} = res;
            if (status === StatusEnum.SUCCESS) {
                const {modules, defuleSelectKeys} = datas;
                // 权限数组
                this.authArr = defuleSelectKeys;
                // 菜单树
                this.modelTree = modules;
                this.role.id = roleId;
                this.isAssigAuthority = true;
            }
        });
    }

    /**
     * 提交权限信息
     */
    submitAuth() {
        this.pageService.setAuth(this.role.id, this.modelTree).subscribe((res: Response) => {
            const {status, message} = res;
            if (status === StatusEnum.SUCCESS) {
                this.message.success(message);
                this.isAssigAuthority = false;
            }
        });
    }

    /**
     * 通过权限id获取角色权限
     * @param role 角色
     */
    role2User(role: Role): void {
        this.pageService.queryUserAuth(role.id).subscribe((res: Response) => {
            const {datas, status} = res;
            if (status === StatusEnum.SUCCESS) {
                this.role = CopyUtil.deepCopy(role, {});
                this.authUsers = datas;
                this.mapOfCheckedId = {};
                this.isAssigUser = true;
                this.isSlectUser = false;
                this.isRemoveSlectUser = false;
            }
        });
    }

    reset(): void {
        this.alertUserName = null;
        this.alertNumber = null;
        this.pageInfo01 = new PageEntity();
        this.pageInfo01.filters['number'.toString()] = undefined;
        this.pageInfo01.filters['name'.toString()] = undefined;
        this.pageQueryUser();
    }

    pageQueryUser(): void {
        this.pageInfo01.first = 1;
        if (this.alertUserName) {
            Object.assign(this.pageInfo01.filters, {name: {value: this.alertUserName, matchMode: FilterEnum.CONTAINS}});
        } else {
            delete this.pageInfo01.filters['name'.toString()];
        }
        if (this.alertNumber) {
            Object.assign(this.pageInfo01.filters, {number: {value: this.alertNumber, matchMode: FilterEnum.CONTAINS}});
        } else {
            delete this.pageInfo01.filters['number'.toString()];
        }
        this.pageFn(this.pageInfo01, this.role.id);

    }

    /**
     * 添加人员弹窗分页
     * @param page:分页参数
     * @param id:id
     */
    pageFn(page: PageEntity, id: string): void {
        this.pageService.pageQueryUser(page, id).subscribe((res: Response) => {
            const {datas, status} = res;
            if (status === StatusEnum.SUCCESS) {
                this.mapOfCheckedId01 = {};
                const {data, totalRecords} = datas;
                this.userList = data;
                this.userList.forEach(item => {
                    if (item.checked) {
                        this.mapOfCheckedId01[item.id] = true;
                    }
                });
                this.pageInfo01.totalRecords = totalRecords;
            }
        });
    }

    /**
     * 单条数据转换选中状态
     * @param item 数据
     * @param event 选中状态
     */
    changeCheack(item, event) {
        item.checked = event;
    }

    /**
     * 选择人员
     */
    selectUserSingle() {
        const arr = [];
        for (const val in this.mapOfCheckedId01) {
            if (this.mapOfCheckedId01[val]) {
                arr[arr.length] = val;
            }
        }
        if (arr.length < 1) {
            this.message.warning('请选择人员!');
            return;
        }
        this.pageService.userAuth(this.role.id, arr).subscribe((res: Response) => {
            const {status, message} = res;
            if (status === StatusEnum.SUCCESS) {
                this.message.success(message);
                this.role2User(this.role);
            }
        });
    }


    clickSearch(): void {
        this.isSlectUser = true;
        this.reset();
    }

    /**
     * 移除具有当前角色的用户
     */
    deleteAuthUserByUID(userId: string): void {
        let ids = [];
        if (userId) {
            ids = [userId];
        } else {
            for (const val in this.mapOfCheckedId) {
                if (this.mapOfCheckedId[val]) {
                    ids[ids.length] = val;
                }
            }
        }
        // if (userId) {
        //     ids = [userId];
        // } else {
        //     this.isRemoveSlectUser = true;
        //     this.authUsers.forEach(item => {
        //         if (!item.checked) {
        //             return;
        //         }
        //         ids.push(item.userId);
        //     });
        // }
        if (ids.length < 1) {
            this.message.warning('请先选择要移除的数据!');
            this.isRemoveSlectUser = false;
            return;
        }
        this.pageService.deleteAuth(this.role.id, ids).subscribe((res: Response) => {
            const {status, message} = res;
            if (status === StatusEnum.SUCCESS) {
                this.role2User(this.role);
                this.mapOfCheckedId = {};
                this.isRemoveSlectUser = false;
                this.message.success(message);
            }
        });
    }

    /**
     * 提交新增编辑角色信息
     */
    submitRole() {
        let submitType = 'create';
        // 如果存在id表示为编辑否则为新增
        if (this.role.id) {
            submitType = 'update';
        }
        // 提交角色信息
        this.pageService[submitType](this.role).subscribe((res: Response) => {
            const {status} = res;
            if (status === StatusEnum.SUCCESS) {
                this.isAddEdit = false;
                this.pageList();
            }
        });
    }
}

